//
//  ZMYCatalogueMoreTableViewController.m
//  奇阅
//
//  Created by 奇阅科技 on 14-10-18.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "ZMYCatalogueMoreTableViewController.h"
#import "Config.h"
#import "BookmarkTableViewCell.h"
#import "ZMYcatalogueRootViewController.h"
#import "SIDownloadManager.h"
#import "SIBreakpointsDownload.h"
#import "PayWebView.h"
#import "BookReadPermissions.h"
@interface ZMYCatalogueMoreTableViewController ()<BookmarkTableViewCellDelegate,PayWebViewDelegate>
{
    NSMutableArray *dataArray;
    NSMutableArray *chapterArray;
    BOOL isHasMore;
    ReadSchedule *readSch;
}
@property (weak,nonatomic)MBProgressHUD *progressHud;
@end

@implementation ZMYCatalogueMoreTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    dataArray = [[NSMutableArray alloc]init];
    if ([self.titleStr isEqualToString:@"书签"]) {
        self.defaultImageView.image = [UIImage imageNamed:@"defaultBookmark"];
        dataArray = [[[ZMYLKDB getLKDBHelper]getBookmarkArticleid:self.book.articleid] mutableCopy];
        chapterArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[[PathHelper documentDirectoryPathWithName:@"db"]
                                                                                   stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ChapterInfo",self.book.articleid]]];
    } else if ([self.titleStr isEqualToString:@"高亮"]) {
        self.defaultImageView.image = [UIImage imageNamed:@"defaultNote"];
        dataArray = [[[ZMYLKDB getLKDBHelper]getHighlightMarkArticleid:self.book.articleid] mutableCopy];
        chapterArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[[PathHelper documentDirectoryPathWithName:@"db"]
                                                                   stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ChapterInfo",self.book.articleid]]];
    } else if ([self.titleStr isEqualToString:@"书评"]) {
        self.defaultImageView.image = [UIImage imageNamed:@"defaultComment"];
    }
    
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.tableView setEditing:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (dataArray.count<1) {
        self.defaultImageView.hidden = NO;
    } else {
        self.defaultImageView.hidden = YES;
    }
    return dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.titleStr isEqualToString:@"书签"]) {
        return 98;
    } else if ([self.titleStr isEqualToString:@"高亮"]) {
        return 98;
    }
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.titleStr isEqualToString:@"书签"]) {
        BookmarkTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BookmarkTableViewCell" forIndexPath:indexPath];
        Bookmark *bookmark = dataArray[indexPath.row];
        for (BookChapterInfo *chapterInfo in chapterArray) {
            if ([chapterInfo.chapterId isEqualToString:bookmark.chapterId]) {
                cell.chapterTitleLabel.text = chapterInfo.chapterName;
                cell.countLabel.text = bookmark.textString;
                break;
            }
        }
        cell.delegate = self;
        return cell;
    } else if ([self.titleStr isEqualToString:@"高亮"]) {
        BookmarkTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BookmarkTableViewCell" forIndexPath:indexPath];
        HighlightMark *bookmark = dataArray[indexPath.row];
        for (BookChapterInfo *chapterInfo in chapterArray) {
            if ([chapterInfo.chapterId isEqualToString:bookmark.chapterId]) {
                cell.chapterTitleLabel.text = chapterInfo.chapterName;
                cell.countLabel.text = bookmark.textString;
                break;
            }
        }
        cell.delegate = self;
        return cell;
    }
    return nil;
}
-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
    return YES;
}
//对一个给定的行告诉代表执行复制或粘贴操作内容,
-(BOOL)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
    if (action==@selector(delete:)) {//如果操作为删除
        return YES;
    }
    return NO;
}
- (void)handleDeleteCell:(BookmarkTableViewCell *)cell{//删除cell
    [self tableView:self.tableView commitEditingStyle:UITableViewCellEditingStyleDelete forRowAtIndexPath:[self.tableView indexPathForCell:cell]];
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        if ([self.titleStr isEqualToString:@"书签"]) {
            Bookmark *bookmark = dataArray[indexPath.row];
            [dataArray removeObjectAtIndex:indexPath.row];
            [[ZMYLKDB getLKDBHelper]deleteToBookmarkDB:bookmark];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        } else if ([self.titleStr isEqualToString:@"高亮"]) {
            HighlightMark *bookmark = dataArray[indexPath.row];
            [dataArray removeObjectAtIndex:indexPath.row];
            [[ZMYLKDB getLKDBHelper]deleteToHighlightMarkDB:bookmark];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@",[NSString stringWithFormat:@"Cell %ld in Section %ld is selected",(long)indexPath.row,(long)indexPath.section]);
    readSch = [ReadSchedule new];
    readSch.articleid = self.book.articleid;
    if ([self.titleStr isEqualToString:@"书签"]) {
        Bookmark *bookmark = dataArray[indexPath.row];
        readSch.chapterId = bookmark.chapterId;
        readSch.rang = bookmark.rang;
    } else if ([self.titleStr isEqualToString:@"高亮"]) {
        HighlightMark *bookmark = dataArray[indexPath.row];
        readSch.chapterId = bookmark.chapterId;
        readSch.rang = bookmark.rang;
    }
#pragma mark 先查看本地有没有阅读权限
    BookReadPermissions *readPer = [BookReadPermissions new];
    readPer.articleid = self.book.articleid;
    readPer.chapterId = readSch.chapterId;
    if (!_progressHud) {
        _progressHud = [MBProgressHUD showHUDAddedTo:[AppDelegate delegate].window animated:YES];
        self.progressHud.removeFromSuperViewOnHide = YES;
        self.progressHud.dimBackground = YES;
        self.progressHud.mode =MBProgressHUDModeDeterminate;
        self.progressHud.detailsLabelText = @"加载中...";
        self.progressHud.removeFromSuperViewOnHide=YES;
    }
    [self.progressHud show:YES];
    [self.progressHud setProgress:0.1];
    if (![readPer getMyReadPermissions]) {
        [self getMyReadPermissions:readSch.chapterId];
    }else{
        [self bookChapterTextVerification:readSch.chapterId];
    }
    
    
}
-(void)getMyReadPermissions:(NSString *)chapterId{
#pragma mark 请求服务器阅读权限
    [[ZMYNetWorkAPI default]getDownloadChapterPermission:chapterId Book:self.book Response:^(NSDictionary *resultDic) {
        NSInteger ret = [[resultDic objectForKey:@"ret"] integerValue];
        switch (ret) {
            case 200:{//可以阅读
                [self bookChapterTextVerification:chapterId];
                break;
            }
                
            case 1:{
                self.progressHud.progress = 0;
                [self.progressHud setHidden:YES];
                [AppDelegate showwarnHUDAndHide:@"章节扣费失败，请登录后继续操作" view:[AppDelegate delegate].window];
                break;
            }
            case 203:{//章节未订阅
                [self chargeForChapters:chapterId];
                break;
            }
            default:{
                self.progressHud.progress = 0;
                [self.progressHud setHidden:YES];
                [AppDelegate showAlert:nil message:@"网络请求失败，请稍后再试"];
                break;
            }
                break;
        }
    } error:^(NSString *errorStr) {
        self.progressHud.progress = 0;
        [self.progressHud setHidden:YES];
        [AppDelegate showAlert:nil message:errorStr];
    }];
}
#pragma mark 章节扣费
-(void)chargeForChapters:(NSString *)autosub_chapters{
    self.progressHud.progress = 0;
    [self.progressHud setHidden:YES];
    UserAccount *user = [UserAccount currentAccount];
    if (!user) {
        self.progressHud.progress = 0;
        [self.progressHud setHidden:YES];
        [AppDelegate showAlert:nil message:@"本章节是VIP章节，请登录后继续操作"];
    }
    PayWebView *view = [[[NSBundle mainBundle]loadNibNamed:@"PayWebView" owner:self options:nil] lastObject];
    //md5(md5（用户ID.时间戳.加密密匙).加密密匙)
    NSString *time = [NSString stringWithFormat:@"%.f",[ZMYNetWorkAPI currentTime]];
    NSString *auth = [[[NSString stringWithFormat:@"%@%@",[[NSString stringWithFormat:@"%@%@%@",user.uid,time,PRIVATE_KEY] md5],PRIVATE_KEY] md5] substringToIndex:10];
    NSString *currentAppVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    
    view.delegate = self;
    //dataapi.yuewen.cc/web//qy_book.php?a=sub_multiple_order&uid=85623598&token=062dd8cb06&auth=3845c90368&t=1419941301004&articleid=1056&textid=27888&srcid=anzhi&v=20&pt=client&ct=android
    view.webUrl = [NSString stringWithFormat:@"http://%@/web/qy_book.php?a=sub_multiple_order&textid=%@&articleid=%@&v=%@&uid=%@&token=%@&t=%@&auth=%@&srcid=iOS&ct=iOS&pay_way=iOS&pt=client",SERVER,autosub_chapters,self.book.articleid,currentAppVersion,user.uid,user.token,time,auth];
    [view showView];
}

#pragma mark 判断本地是否有该章节内容
-(void)bookChapterTextVerification:(NSString *)chapterId{
    if ([[ZMYLKDB getLKDBHelper]getBookChapterTextWithArticleid:self.book.articleid chapterId:chapterId]) {
        //判断本地是否有该章节内容
        [self.progressHud setProgress:1];
        [self.progressHud setHidden:YES];
        [self transitionToReadView:chapterId];
    }else{
        [self.progressHud setProgress:0.6];
        //如果本地没有该章节内容
        [self downloadChapterText:chapterId];
    }
}
-(void)downloadChapterText:(NSString *)chapterId{
#pragma mark 下载章节内容
    __weak typeof(self) weakSlef = self;
    NSString *purviewMark = [[NSString stringWithFormat:@"%@%@",chapterId,chapterId] md5];
    purviewMark = [[NSString stringWithFormat:@"qy_%@",purviewMark] md5];
    NSString *currentAppVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    NSString *urlStr = [NSString stringWithFormat:@"http://%@/web/qy_book.php?a=download_articleid&purviewMark=%@&chapterids=%@&output=txt&ct=iOS&v=%@&srcid=iOS",SERVER,purviewMark,chapterId,currentAppVersion];
    NSString *downloadPath = [[PathHelper cacheDirectoryPathWithName:@"Lib"]stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@%@",self.book.articleid,chapterId,chapterId]];
    SIDownloadManager *siDownloadManager = [SIDownloadManager sharedSIDownloadManager];
    [siDownloadManager  addDownloadFileTaskInQueue:urlStr toFilePath:downloadPath breakpointResume:YES rewriteFile:NO DidComplete:^(SIDownloadManager *siDownloadManager, SIBreakpointsDownload *paramOperation) {
        if ([paramOperation.downloadFilePath isEqualToString:downloadPath]) {
            if ([[ZMYLKDB getLKDBHelper]unarchiveFreeChapter:downloadPath Book:weakSlef.book]) {
                [weakSlef.progressHud setProgress:1];
                [weakSlef.progressHud setHidden:YES];
                [weakSlef transitionToReadView:chapterId];
            }else{
                [weakSlef.progressHud setProgress:1];
                [weakSlef.progressHud setHidden:YES];
                [AppDelegate showHUDAndHide:@"章节下载失败" view:[AppDelegate delegate].window];
            }
        }
    } Progress:^(SIDownloadManager *siDownloadManager, SIBreakpointsDownload *paramOperation, double paramProgress) {
        if ([paramOperation.downloadFilePath isEqualToString:downloadPath]) {
            [weakSlef.progressHud setProgress:paramProgress];
        }
    } Error:^(SIDownloadManager *siDownloadManager, SIBreakpointsDownload *paramOperation, NSError *paramError) {
        if ([paramOperation.downloadFilePath isEqualToString:downloadPath]) {
            NSLog(@"%@ withError:%@",paramOperation.url,paramError.localizedDescription);
            [weakSlef.progressHud setProgress:0];
            [weakSlef.progressHud setHidden:YES];
            [AppDelegate showHUDAndHide:paramError.localizedDescription view:[AppDelegate delegate].window];
        }
        
    }];
}
-(void)transitionToReadView:(NSString *)chapterId{
#pragma mark 跳转到阅读页
    [[ZMYLKDB getLKDBHelper]updateReadSchedule:readSch];
    ZMYcatalogueRootViewController *iter = [self frostedSettingCollectionViewController];
    if (iter) {
        [iter toReadView:nil];
    }
}
- (ZMYcatalogueRootViewController *)frostedSettingCollectionViewController
{
    UIViewController *iter = self.parentViewController;
    while (iter) {
        if ([iter isKindOfClass:[ZMYcatalogueRootViewController class]]) {
            return (ZMYcatalogueRootViewController *)iter;
        } else if (iter.parentViewController && iter.parentViewController != iter) {
            iter = iter.parentViewController;
        } else {
            iter = nil;
        }
    }
    return nil;
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - XLSwipeContainerItemDelegate
#pragma mark - THSegmentedPageViewControllerDelegate
- (NSString *)viewControllerTitle
{
    return self.titleStr;
}
@end
